/**
 * sticker选择tab 
 */
var emojiSelectorTab = (function() {   
    var emojiSelectorTabObj;
    var loadStickerList;
    var refreshTab;
    var filterCat;
    
    function addSticker(sticker, index){
        var cookiedS = JSON.parse($.cookie('sticker_list') || '[]');
        
        if(Type.isUndefined(index)){
            index = emojiSelectorTabObj.getTabsCount();
        }
        var page0 = sticker;
        var page0Bg = '/rest/apis/sticker/{0}/image/{1}'.format(page0['id'], page0['backgrounds'][0]);
        
        emojiSelectorTabObj.ddMenu.addItem({
            id : sticker['id'],
            name : sticker['name'],
            index : index
        });
        
        emojiSelectorTabObj.addTabItem({
            id : sticker['id'],
            title : sticker['name'],
            html : '<div class="iconWrapper" style="margin:8px;"></div>'
        }, function($stickerWrapper, $tabNavItem){  
            //if(index > 5) $tabNavItem.hide();   
            if(!cookiedS.contains(sticker['id'])){
                $tabNavItem.hide();
            }               
            var stickerSelector = new IconSelector($stickerWrapper.find('.iconWrapper'), {
                name : sticker['title'],
                iconBg : page0Bg,
                width : 602,
                iconCls : '',
                rowIconCount : 7,
                itemWidth : 80,
                itemHeight : 80,
                iconCount : sticker.stickers.length,
                cellPadding : 7
            }); 
            stickerSelector.on('itemClick', function(opt){  
                var stickerMeta = sticker.stickers[opt['index']];    
                var stickerPost = {
                    "rid" : stickerMeta['rid'],
                    'suitID' : sticker['id'],                    
                    "name" : stickerMeta['title']
                };
                if(stickerMeta['s']){
                    stickerPost['width'] = stickerMeta['s'][0];
                    stickerPost['height'] = stickerMeta['s'][1];
                }                           
                MsgSender.send('sticker', stickerPost);
                emojiSelectorTab.hide();
            });
        });
    };

    return Observable.create({
        init : function() {},
        show : function(dom) {            
            var _this = this;
            if(!this.isInitialized){
                this.$wrapper = $('<div id="iconSelector"></div>').appendTo(document.body);
                //延迟初始化.
                emojiSelectorTabObj = this.$wrapper.css({
                    visibility : 'hidden'
                }).show().tabControl({                    
                    showToolbar : true,
                    //closable : true,
                    hideNavBarWhenOnlyOneItem : false,
                    onInit : function(){
                        var _this = this;
                        this.$ddMenu = $('<div class="stickerMenu"><div></div></div>');
                        this.$ddMenu.hideOnClickDoc(function(){                           
                            //emojiSelectorTabObj.selectFirstVisibleTab();
                        });
                        this.$ddMenu.appendTo(this.$wrapper);                        
                        this.ddMenu = this.$ddMenu.find('>div').listView({
                            itemTmp : [
                                '<div class="stickerMenuItem" stickerid="<%=o.id%>" title="<%=o.name%>">',
                                    '<span class="stickerMenuItemChecker"><input type="checkbox" value="<%=o.id%>" <%= JSON.parse($.cookie("sticker_list") || "[]").contains(o.id) ? "checked" : "" %> /></span>',
                                    '<span class="stickerNameMenu"><%=o.name%></span>',
                                    '<span stickerid="<%=o.id%>" class="delStickerMenu hidden">X</span>',
                                '</div>'
                            ].join(''),                            
                            events : {}
                        }).data('listView');
                          
                        refreshTab = function(chk){                            
                            
                            var id = $(chk).val();
                            var cookiedS = JSON.parse($.cookie('sticker_list') || '[]');
                            if($(chk).is(":checked")){
                                cookiedS.unshift(id);
                                if(cookiedS.length > 6){                                    
                                    var removeID = cookiedS.pop();
                                    $('input[value={0}]'.format(removeID)).prop('checked', false);
                                }
                            } else {
                                cookiedS.remove(id);
                            }
                            $.cookie('sticker_list', JSON.stringify(cookiedS), {
                                expires : Date.nowDateObj().add('y', 1000)
                            });

                            var ss = _this.$ddMenu.find('input:checked');
                            emojiSelectorTabObj.hideAllTab();
                            for(var j=0; j<ss.length && j < 6; j++){
                                emojiSelectorTabObj.showTab($(ss[j]).val());
                            }
                            if($(chk).is(":checked")){
                                emojiSelectorTabObj.select($(chk).attr('value'));
                            }                            
                        };
                        
                        this.$ddMenu.delegate('input[type=checkbox]', 'change', function(){
                            refreshTab(this);
                        });
                        this.$ddMenu.delegate('.delStickerMenu', 'click', function(){
                            var $self = $(this).closest('.listViewItem');
                            var stickerID = $(this).attr('stickerid');
                            bubble.confirm('Delete this sticker?', function(){
                                $.ajax({
                                    type : 'delete',
                                    url : "/apis/sticker/mine/" + stickerID,
                                    success : function(){
                                        $self.remove();
                                        page.mySIDs.remove(stickerID);    
                                        refreshTab();
                                    } 
                                });
                            });
                        });
                        this.$tip = $('<div class="stickerTip emptyTip">You have no sticker yet, click plus button to add some.</div>');
                        this.$tip.hide();
                        this.$tip.appendTo(this.$wrapper);  
                    }
                }).data('tabControl');  
                              
                emojiSelectorTabObj.toolbar.addImageButton({
                    id : 'showMenu',
                    image : ujs.getRes('images/common16/tools.png'),
                    tooltip : 'Show All Sticker',
                    cls : 'icon imageBtn',
                    onClick : function() {
                        emojiSelectorTabObj.$ddMenu.fadeToggle();
                    }
                });
                
                emojiSelectorTabObj.toolbar.addImageButton({
                    id : 'addSticker',
                    image : ujs.getRes('images/common16/add2.png'),
                    tooltip : 'Add Sticker',
                    cls : 'icon imageBtn',
                    onClick : function() {
                        emojiSelectorTabObj.select(page.addStickerID);
                        emojiSelectorTabObj.$tip.remove();
                        (function(){
                            loadStickerList('all');
                            $.get('/apis/sticker/categories', ujs.hr( function( msg ){
                                filterCat.refresh(msg['categories']);                                
                            }));                            
                        }).defer(5);
                    }
                });
                $.ajax({
                    url : '/apis/sticker/mine',
                    success : function(meta){
                        var stickers = JSON.insure(meta)['suits'];  
                        page.mySIDs = stickers.map(function(item){
                            return item.id;
                        });                       
                        for(var i=0; i<stickers.length; i++){
                            addSticker(stickers[i], i);
                        }
                        if(!stickers.length){
                            emojiSelectorTabObj.$tip.show();
                        } else {
                            emojiSelectorTabObj.$tip.remove();
                        }
                        page.addStickerID = String.newGuid();
                        
                        (function(){
                            //默认选中第一项.
                            emojiSelectorTabObj.selectFirstVisibleTab();    
                        }).defer();                        
                        
                        emojiSelectorTabObj.addTabItem({
                            id : page.addStickerID,
                            title : 'AddSticker',
                            html : [
                                '<div class="iconWrapper" style="margin:8px;">',
                                    '<div><span>Category:</span><div class="catsList"></div></div>',
                                    '<div class="stickerList"></div>',
                                '</div>'
                            ].join('')
                        }, function($stickerWrapper, $navItem){
                            
                            $navItem.hide();
                            //类别选择框.
                            filterCat = $stickerWrapper.find('.catsList').selectBox({
                                width: 207,
                                style : 'margin-bottom: 3px;margin-top: 1px;line-height:24px;',
                                initData : {            
                                    id : 'all',
                                    name : 'All'    
                                },
                                value : 'all',
                                data : {
                                    url : '/apis/sticker/categories',
                                    root : 'categories',
                                    mapping : {
                                        text : 'name',
                                        value : 'id'
                                    }
                                },
                                onchange : function(val){
                                    loadStickerList(val);
                                }
                            });
                            
                            var stickerList = $stickerWrapper.find('.stickerList').listView({
                                    itemTmp : [
                                        '<div class="stickerItem column3" id="<%=o.id%>">',
                                            '<div style="width:80px;height:80px;text-align: center;" class="c1 hvBox">',
                                                '<img style="max-width:80px;max-height:80px;" src="/rest/apis/sticker/<%=o.id%>/image/<%=o.thumbnail%>" />',
                                            '</div>',                                            
                                            '<div class="c2">',
                                                '<h2><%=o.name%></h2>',
                                                '<div><%=o.desc%></div>',
                                            '</div>',
                                            '<div class="c3">',
                                                '<span><%=(new Date(o.createTime)).format("yyyy-MM-dd")%></span><br/>',
                                                '<span>',
                                                    '<% if(page.mySIDs.contains(o.id)) { %>',
                                                        '<img src="/ujs/images/common16/yes.png" style="vertical-align: text-bottom;" />',
                                                    '<% } else { %>',
                                                        '<button class="addMySticker <%=page.mySIDs.contains(o.id)? "mySticker" : "" %>"><%=page.mySIDs.contains(o.id) ? "Remove" : "Add" %></button>',
                                                    '<% } %>',
                                                '</span>',
                                            '</div>',
                                        '</div>'
                                    ].join(''),
                                    
                                    style : '',        
                                    events : {
                                        init : function(){
                                            this.$wrapper.delegate('.stickerItem .addMySticker', 'click', function(){
                                                var $self = $(this);
                                                var id = $(this).closest('.stickerItem').attr('id');
                                                if(!$self.hasClass('mySticker')){
                                                    $.post("/apis/sticker/mine/" + id, function(){
                                                        $self.parent().html('<img src="/ujs/images/common16/yes.png" style="vertical-align: text-bottom;" />');
                                                        $self.addClass('mySticker');
                                                        page.mySIDs.add(id);
                                                        addSticker(stickerList.store.getItem(id));
                                                        (function(){
                                                            //emojiSelectorTabObj.select(id);
                                                            var $chk = emojiSelectorTabObj.$ddMenu.find(':checkbox[value={0}]'.format(id));
                                                            $chk.prop('checked', true);
                                                            refreshTab($chk.get(0));
                                                        }).defer(0);
                                                    });    
                                                } else {
                                                    $.ajax({
                                                        type : 'delete',
                                                        url : "/apis/sticker/mine/" + id,
                                                        success : function(){
                                                            $self.text('Add');    
                                                            page.mySIDs.remove(id);
                                                            emojiSelectorTabObj.deleteTab(id);
                                                        } 
                                                    });
                                                }
                                            });
                                        },
                                        itemClick : function($listViewItem, itemID){
                                            var currentItem = this.getCurrentDataItem();                                            
                                        }
                                    }
                                }
                            ).data('listView');
                                                        
                            loadStickerList = function(val){
                                $.get('/apis/sticker/suits' + (val == 'all' ? "" : '/' + val), ujs.hr( function( msg ){
                                    stickerList.load(msg['suits']);
                                }));
                            };
                            loadStickerList('all');
                        });
                    } 
                });
                
                _this.$wrapper.hideOnClickDoc(function(){
                    _this.hide();
                });
                
                this.isInitialized = true;    
            }
            var domPos = $(dom).offset();
            this.$wrapper.css({
                left : domPos.left - 3,
                top : domPos.top - this.$wrapper.outerHeight() - 10,
                visibility : 'visible'
            }).fadeIn(500, 'easeOutExpo');
        },
        getTabControl : function(){
            return emojiSelectorTabObj;
        },
        isVisible : function(){
            return this.$wrapper ? this.$wrapper.stop().is(':visible') : false;
        },
        hide : function() {
            this.$wrapper.fadeOut(500, 'easeOutExpo');
        },
        getCokie : function(){
            return JSON.parse($.cookie('sticker_list') || '[]');
        },
        setCokie : function(stickerIDs){
            $.cookie('sticker_list', JSON.stringify(stickerIDs), {
                expires : Date.nowDateObj().add('y', 1000)
            });
        }
    });
})();